package com.example.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.common.CustomException;
import com.example.takeaway.common.R;
import com.example.takeaway.entity.Category;
import com.example.takeaway.entity.Dish;
import com.example.takeaway.entity.Setmeal;
import com.example.takeaway.mapper.CategoryMapper;
import com.example.takeaway.service.CategoryService;
import com.example.takeaway.service.DishService;
import com.example.takeaway.service.SetMealService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    private final DishService dishService;
    private final SetMealService SetMealService;


    /**
     * 根据id删除分类 删除之前需要进行判断
     * @param ids
     */

    @Override
    public void remove(Long ids) {

        //查询当前分类下是否关联了菜品 如果已经关联 抛出一个业务异常   --> 看菜品表的categoryId有没有 和 传来的id相同
        // select count(*) from dish where category_id = 139784263642378242

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
        long count = dishService.count(dishLambdaQueryWrapper);

        if(count > 0){
            // 已关联菜品 抛出一个异常
            throw new CustomException("当前分类下关联了菜品 不能删除");

        }

        //查询当前分类是否关联了套餐 如果已经关联 抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId ,ids);
        long count1 = SetMealService.count(setmealLambdaQueryWrapper);
        if(count1 > 0){
            //已关联套餐
            throw new CustomException("已经关联了套餐 不能删除");
        }

        //正常删除分类
        removeById(ids);

    }



}
